package com.dm.wallpaper.library.fraction;

import com.dm.wallpaper.library.ResourceTable;
import com.dm.wallpaper.library.ablility.slice.WallpaperBoardBrowserAbilitySlice;
import com.dm.wallpaper.library.database.Database;
import com.dm.wallpaper.library.items.Filter;
import com.dm.wallpaper.library.items.PopupItem;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.preferences.Preferences;
import com.dm.wallpaper.library.utils.Log;
import com.dm.wallpaper.library.utils.DialogUtils;
import com.dm.wallpaper.library.utils.Extras;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.element.VectorElement;
import ohos.agp.window.service.WindowManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class CateoryWallpaperSearchFraction extends Fraction implements Component.ClickedListener, Component.FocusChangedListener {
    Component component;
    TextField searchContent;
    Text showSearchInfo;
    Component tablayout;
    Component showSearchInfoLayout;
    Image rightMuneIcon;
    String cateoryName;
    int cateoryNumber;
    Image clickSearch;

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        component = scatter.parse(ResourceTable.Layout_fraction_cateory_browser_search, null, false);
        cateoryName = getFractionAbility().getIntent().getStringParam(Extras.EXTRA_CATEGORY);
        cateoryNumber = getFractionAbility().getIntent().getIntParam(Extras.EXTRA_COUNT, 0);
        addTitleInfo(cateoryName, cateoryNumber);
        return component;
    }


    @Override
    protected void onActive() {
        super.onActive();
        initView();
    }

    private void initView() {
        component.findComponentById(ResourceTable.Id_left_mune_icon).setClickedListener(this);
        searchContent = (TextField) component.findComponentById(ResourceTable.Id_search_content);
        showSearchInfo = (Text) component.findComponentById(ResourceTable.Id_show_search_info);
        showSearchInfoLayout = component.findComponentById(ResourceTable.Id_show_search_info_layout);
        searchContent.setVisibility(Component.INVISIBLE);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(new RgbColor(0x00000000));
        searchContent.setBubbleElement(shapeElement);
        clickSearch = (Image) component.findComponentById(ResourceTable.Id_click_search);
        clickSearch.setVisibility(Component.VISIBLE);
        clickSearch.setClickedListener(this);
        String titleSearch = "";
        try {
            titleSearch = getFractionAbility().getResourceManager().getElement(ResourceTable.String_menu_search).getString();
        } catch (Exception e) {
        }

        searchContent.setHint(titleSearch);
        rightMuneIcon = (Image) component.findComponentById(ResourceTable.Id_right_mune_icon);
        VectorElement vectorElement = new VectorElement(getFractionAbility(), ResourceTable.Graphic_svg_toolbar_sort);
        rightMuneIcon.setImageElement(vectorElement);
        rightMuneIcon.setClickedListener(this);
        searchContent.setFocusChangedListener(this);
        addTextCouseListener();

        Filter filter = new Filter();
        filter.add(Filter.Create(Filter.Column.CATEGORY).setQuery(cateoryName));
        List<Wallpaper> wallpapers = Database.get().getFilteredWallpapers(filter);
        addTablayout(wallpapers);
    }


    private void addTitleInfo(String name, int count) {
        DirectionalLayout title_info = (DirectionalLayout) component.findComponentById(ResourceTable.Id_title_info);
        title_info.setVisibility(Component.VISIBLE);
        DirectionalLayout directionalLayout = (DirectionalLayout) LayoutScatter.getInstance(getFractionAbility()).parse(ResourceTable.Layout_title_info_layout, null, false);
        Text text_wallpapers_title = (Text) directionalLayout.findComponentById(ResourceTable.Id_text_wallpapers_title);
        Text text_wallpapers_info = (Text) directionalLayout.findComponentById(ResourceTable.Id_text_wallpapers_info);
        text_wallpapers_title.setText(name);
        text_wallpapers_info.setText(count + " Wallpapers");
        title_info.addComponent(directionalLayout);
    }

    private void addTextCouseListener() {
        try {
            Class clazz = Class.forName("ohos.agp.components.TextField$CursorChangedListener");
            Object mObj = Proxy.newProxyInstance(WallpaperBoardBrowserAbilitySlice.class.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
                @Override
                public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                    if (method.getName().equals("onCursorChange")) {
                        TextField textField = (TextField) objects[0];

                        textChange(textField);

                    }
                    return null;
                }
            });
            Method mMethod = searchContent.getClass().getDeclaredMethod("setCursorChangedListener", new Class[]{clazz});
            mMethod.setAccessible(true);
            mMethod.invoke(searchContent, new Object[]{mObj});
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("WallpaperBoardBrowserAbilitySlice.initView([]):74  反射报错了:" + e.getLocalizedMessage());
        }
    }


    public void textChange(TextField textField) throws NotExistException, WrongTypeException, IOException {
        String text = textField.getText();
        text = text.replace(" ", "");
        text = text.replace("\n", "");
        text = text.replace("\"", "");
        Filter filter = new Filter();
        if (text.equals("")) {
            text = cateoryName;
        }
        filter.add(Filter.Create(Filter.Column.CATEGORY).setQuery(text));
        List<Wallpaper> wallpapers = Database.get().getFilteredWallpapers(filter);
        String showInfo = getFractionAbility().getResourceManager().getElement(ResourceTable.String_search_result_empty).getString();
        if (wallpapers == null || wallpapers.size() == 0) {
            showSearchInfo.setText(showInfo + "\"" + text + "\"");
            showSearchInfoLayout.setVisibility(Component.VISIBLE);
        } else {
            showSearchInfoLayout.setVisibility(Component.HIDE);
        }
        if (!text.equals("")) {
            VectorElement vectorElement = new VectorElement(getFractionAbility(), ResourceTable.Graphic_svg_toolbar_close);
            clickSearch.setImageElement(vectorElement);
            clickSearch.setVisibility(Component.VISIBLE);
        } else {
            clickSearch.setVisibility(Component.HIDE);
            showSearchInfoLayout.setVisibility(Component.HIDE);
        }
        addTablayout(wallpapers);
    }


    private void addTablayout(List<Wallpaper> wallpapers) {
        DirectionalLayout scroll_table = (DirectionalLayout) (component.findComponentById(ResourceTable.Id_scroll_table));
        if (tablayout != null) {
            scroll_table.removeComponent(tablayout);
        }
        if (wallpapers == null || wallpapers.size() == 0) {
            scroll_table.setVisibility(Component.HIDE);
            return;
        }
        scroll_table.setVisibility(Component.VISIBLE);
        tablayout = ContentCompentUtils.initWallpaperView(wallpapers, getFractionAbility());
        scroll_table.addComponent(tablayout);
    }


    @Override
    public void onClick(Component component) {
        if (component.getId() == ResourceTable.Id_left_mune_icon) {
            if (searchContent.getText().equals("")) {
                Fraction fraction = FractionHelper.getInstance(getFractionAbility()).gotoLastFraction();
                if (fraction == null) {
                    getFractionAbility().terminateAbility();
                }
            } else {
                try {
                    searchContent.setText("");
                    textChange(searchContent);
                } catch (Exception e) {

                }

            }
        } else if (component.getId() == ResourceTable.Id_right_mune_icon) {
            DialogUtils.getInstance().showSortDialog(getFractionAbility(), rightMuneIcon, new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    if (component.getId() == ResourceTable.Id_sort_latest) {
                        Preferences.get().setSortBy(PopupItem.Type.SORT_LATEST);
                    } else if (component.getId() == ResourceTable.Id_sort_oldest) {
                        Preferences.get().setSortBy(PopupItem.Type.SORT_OLDEST);
                    } else if (component.getId() == ResourceTable.Id_sort_name) {
                        Preferences.get().setSortBy(PopupItem.Type.SORT_NAME);
                    } else if (component.getId() == ResourceTable.Id_sort_random) {
                        Preferences.get().setSortBy(PopupItem.Type.SORT_RANDOM);
                    }
                    Filter filter = new Filter();
                    filter.add(Filter.Create(Filter.Column.CATEGORY).setQuery(cateoryName));
                    List<Wallpaper> wallpapers = Database.get().getFilteredWallpapers(filter);
                    addTablayout(wallpapers);
                }
            });
        } else if (component.getId() == ResourceTable.Id_click_search) {
            component.setVisibility(Component.INVISIBLE);
            searchContent.setText("");
            searchContent.setVisibility(Component.VISIBLE);


            searchContent.requestFocus();
            searchContent.simulateClick();

            clickSearch.setVisibility(Component.HIDE);
            showSearchInfoLayout.setVisibility(Component.HIDE);
            Filter filter = new Filter();
            filter.add(Filter.Create(Filter.Column.CATEGORY).setQuery(cateoryName));
            List<Wallpaper> wallpapers = Database.get().getFilteredWallpapers(filter);
            addTablayout(wallpapers);
        }
    }

    @Override
    public void onFocusChange(Component component, boolean b) {
        if (component.getId() == ResourceTable.Id_search_content) {
            if (b) {
                getFractionAbility().getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN);
            } else {
                getFractionAbility().getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_STATE_VISIBLE);
            }
        }
    }
}
